#include "MarkDownEdit.h"

#include "strings.h"
#include "sundown/markdown.h"
#include "sundown/html.h"

#include <sstream>
#include <string>

#include "qlayout.h"
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qcombobox.h>
#include <qfontcombobox.h>
#include <qtextedit.h>

MarkDownEdit::MarkDownEdit(QWidget* parent) : NoteEdit(parent)
{
	layout = new QGridLayout();

	QFontComboBox* fontFamilyBox = new QFontComboBox();

	QToolButton* addImgBtn = new QToolButton();
	addImgBtn->setIcon(QIcon("Resources/image.png"));
	addImgBtn->setToolTip(STRINGS::INSERT_IMAGE);

	QToolButton* fenceBtn = new QToolButton();
	fenceBtn->setIcon(QIcon("Resources/fence.png"));
	fenceBtn->setToolTip(STRINGS::SPLIT);

	QToolButton* readModeBtn = new QToolButton();
	readModeBtn->setIcon(QIcon("Resources/read.png"));
	readModeBtn->setToolTip(STRINGS::READ_MODE);

	toolBar->addWidget(fontFamilyBox);
	toolBar->addWidget(addImgBtn);
	toolBar->addWidget(fenceBtn);
	toolBar->addWidget(readModeBtn);
	
	sourceBoard = new QTextEdit();
	displayBoard = new QTextEdit();
	displayBoard->setReadOnly(true);

	layout->addWidget(toolBar, 0, 0, 1, 2);
	layout->addWidget(sourceBoard, 1, 0, 1, 1);
	layout->addWidget(displayBoard, 1, 1, 1, 1);

	setLayout(layout);

	connect(sourceBoard, SIGNAL(textChanged()), SLOT(displayMarkDown()));
}


MarkDownEdit::~MarkDownEdit()
{
}

void MarkDownEdit::displayMarkDown()
{
	
	
	const int READ_UNIT = 1024;
	const int OUTPUT_UNIT = 64;

	struct buf *ob;
	struct sd_callbacks callbacks;
	struct html_renderopt options;
	struct sd_markdown *markdown;

	ob = bufnew(OUTPUT_UNIT);
	sdhtml_renderer(&callbacks, &options, 0);
	markdown = sd_markdown_new(MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES | MKDEXT_AUTOLINK | MKDEXT_FENCED_CODE | MKDEXT_STRIKETHROUGH | MKDEXT_SUPERSCRIPT, 16, &callbacks, &options);

	std::string stdSourceStr = sourceBoard->toPlainText().toStdString();
	sd_markdown_render(ob, (const uint8_t*)(stdSourceStr.c_str()), stdSourceStr.length(), markdown);

	sd_markdown_free(markdown);

	std::stringbuf sb;
	sb.sputn((const char*)ob->data, ob->size);

	bufrelease(ob);

	std::string head = "<html><head><link href=\"resources/basestyle.css\" rel=\"stylesheet\" type=\"text/css\" /></head><body>";
	std::string tail = "</body></html>";
	std::string htmlStr = head + sb.str() + tail;
	displayBoard->setHtml(QString(htmlStr.c_str()));
	
}